package top.yongyan0624.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yongyan0624.common.lang.CodeMsg;
import top.yongyan0624.common.lang.ResultVO;
import top.yongyan0624.entity.Notice;
import top.yongyan0624.entity.SysUser;
import top.yongyan0624.service.NoticeService;
import top.yongyan0624.service.SysUserService;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-06-01
 */
@RestController
public class NoticeController extends BaseController {

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private SysUserService sysUserService;

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @PostMapping("/home/submitNotice")
    public ResultVO submitNotice(@RequestBody Notice notice) {
        notice.setTime(LocalDateTime.now());

        boolean ok = noticeService.save(notice);

        if (ok){
            return ResultVO.success("发布成功！");
        }
        return ResultVO.error(new CodeMsg("对不起，发布公告失败！"));
    }

    @RequestMapping("/home/getNotice")
    public ResultVO getNotice() {
        List<Notice> noticeList = noticeService.list();

        for (Notice notice : noticeList) {
            SysUser user = sysUserService.getById(notice.getUserId());
            notice.setUserName(user.getUsername());
        }

        return ResultVO.success(noticeList);
    }

}
